using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;
using Demo.Domain.NHibernate;
using Demo.Models;
using WB.Mvc.Forms;
using Demo.Controllers;

namespace Demo.Controllers
{
	[HandleError]
	public class PostsController : Controller
	{
		public PostsController()
		{
			// TODO: Use IoC
			PostRepository = new PostReposiotry();
		}

		public IRepository<Post> PostRepository { get; set; }

		public object Index()
		{
			IEnumerable<Post> posts = PostRepository.FindAll();

			return View(posts);
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public object Show(int id)
		{
			Post post = PostRepository.Find(id);

			return View(post);
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public object New()
		{
			PostModelForm form = (PostModelForm) TempData["Form"] ?? new PostModelForm(new Post()) {Action = "Create"};
			return View(form);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public object Create(PostModelForm post)
		{
			if (!post.IsValid())
			{
				TempData["Form"] = post;
				return RedirectToAction("New");
			}

			PostRepository.Save(post.Model);

			return RedirectToAction("Index");
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public object Edit(int id)
		{
			Post post = PostRepository.Find(id);
			if (post == null)
			{
				TempData["Notice"] = "Post not found.";
				return RedirectToAction("Index");
			}

			PostModelForm form = (PostModelForm) TempData["Form"] ?? new PostModelForm(post);
			form.Action = Url.Action("Update", "Posts", new {}, "http");
			form.Method = FormMethod.Post;

			return View(form);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public object Update(PostModelForm form)
		{
			Post post = PostRepository.Find(Convert.ToInt32(form.UniqueIdentifier));

			form.Model = post;
			form.Load(Request.Form);

			if (!form.IsValid())
			{
				TempData["Form"] = form;
				return RedirectToAction("Edit");
			}

			TempData["Notice"] = "Updated the post.  Thank you.";
			return RedirectToAction("Index");
		}
	}

	public class PostModelForm : ModelForm<Post>
	{
		public PostModelForm()
		{
		}

		public PostModelForm(Post model) : base(model)
		{
			FieldGroups.First().Legend = new XElement("legend", "Post");
			FieldGroups.Last().Legend = new XElement("legend", "Author");
		}
	}
}